package com.lx.flutest.flu

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.lx.fluplugin.FlupluginPlugin
import com.lx.fluplugin.R
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
import java.util.Objects

class FluView(context: Context?, viewId: Int, args: Any?,binaryMessenger: BinaryMessenger) : PlatformView,
    MethodChannel.MethodCallHandler {

    private lateinit var methodChannel : MethodChannel
    private lateinit var context: Context
    private val binaryMessenger: BinaryMessenger
    private lateinit var arguments : MutableMap<String,Objects>

    private lateinit var rootView : View
    private lateinit var txtView : TextView
    private lateinit var btnButton : Button

    private var num : Int = 1

    init {
        this.binaryMessenger = binaryMessenger
        this.context = context!!
        if(args!=null){
            this.arguments = args as MutableMap<String, Objects>
        }
        rootView = LayoutInflater.from(context).inflate(R.layout.flu_view, null, false)
        txtView = rootView.findViewById<TextView>(R.id.txtView);
        btnButton = rootView.findViewById<Button>(R.id.btnButton);
        var numTemp = arguments["num"] as Int
        txtView.text = "我是原生View，接收flutter端传过来的参数为：${numTemp}"
        btnButton.setOnClickListener({
            num ++
            Log.e("FluView","btnButton-->${num}")
            var postArgs = HashMap<String,Any>()
            postArgs["num"] = num

            FlupluginPlugin.eventSink?.success(postArgs)
        })
    }

    public fun initChannel(){
        methodChannel = MethodChannel(binaryMessenger,"com.lx.FluView.methodChannel")
        methodChannel.setMethodCallHandler(this)
    }

    override fun getView(): View? {


        return  rootView
    }

    override fun dispose() {
        methodChannel.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        print("--->call=${call.method}")
        print("--->argumentsTemp=${call.arguments}")

        Log.e("FluView","call-->${call.method}")
        Log.e("FluView","argumentsTemp-->${call.arguments}")
        var argumentsTemp = call.arguments as? MutableMap<String,Objects>
        when(call.method){
            "addNum"->{
                if(argumentsTemp!=null){
                    var numTemp = argumentsTemp["num"] as Int
                    txtView.text = "我是原生View，接收flutter端传过来的参数为：${numTemp}"
                }
            }
        }
    }
}